<?php
namespace Admin\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Paginator\Paginator;
use Zend\Paginator\Adapter\DbSelect as PaginatorAdapter;

class SongTable extends AbstractTableGateway {
	
	protected $table = 'song';
	
	public function __construct(Adapter $adapter) {
		$this->adapter = $adapter;
		$this->resultSetPrototype = new ResultSet();
		$this->resultSetPrototype->setArrayObjectPrototype(new Song());
		$this->initialize();
	}
	
	public function getPage($params) {
		if(!isset($params['page'])) $params['page'] = 1;
		if(!isset($params['user_id'])) $params['user_id'] = '%%';
		$select = $this->getSql()->select()->where("user_id LIKE '" . $params['user_id'] . "'");
		$adapter = new PaginatorAdapter($select, $this->adapter);
		$paginator = new Paginator($adapter);
		$paginator->setCurrentPageNumber($params['page']);
		$res = $paginator;
		return $res;
	}
	
	public function getSong($id) {
		$id = (int)$id;
		$rowset = $this->select(array('id'=>$id));
		$row = $rowset->current();
		if(!$row) {
			throw new \Exception("Could not find row " . $id);
		}
		return $row;
	}
	
	public function saveSong(Song $song) {
		$data = array();
		foreach($song as $key=>$value) {
			$data[$key] = $value;
		}
		$id = (int)$song->id;
		if(empty($id)) {
			$this->insert($data);
		} else {
			if($this->getSong($id)) {
				$this->update($data, array('id'=>$id));
			} else {
				throw new \Exception('Form id does not exist');
			}
		}
	}
	
	function deleteSong($id) {
		$this->delete(array('id'=>$id));
	}
}